﻿using Demo.Net.SqlSugar;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class SqlSugarDBComExtensions
    {

        /// <summary>
        ///使用sqlsugar连接pgsql
        /// </summary>
        /// <returns></returns>
        public static IServiceCollection AddSqlSugarExtensions(this IServiceCollection services, IConfiguration configuration)
        {

            services.AddScoped<ISqlSugarClient>(sp =>
            {
                var sugarOptions = new ConnectionConfig
                {
                    ConnectionString = $"{configuration["PgSqlConnectionString"]};ApplicationName={Assembly.GetEntryAssembly()?.GetName().Name}",
                    DbType = DbType.PostgreSQL,
                    IsAutoCloseConnection = true
                };

                var sugarClient = new SqlSugarClient(sugarOptions)
                {
                    Ado = { CommandTimeOut = 120 },
                    Aop =
                    {
                        OnLogExecuting = (sql, pars) =>
                        {
                             switch (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"))
                             {
                                 case "Development":
                                 case "Staging":
                                     {
                                         Console.WriteLine(sql + "\r\n" + JsonSerializer.Serialize(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                                         Console.WriteLine();
                                         break;
                                     }
                                 case "Production": break;
                             
                             }
                        }
                    }
                };

                return sugarClient;
            });
            //注入事务方法
            services.AddScoped<ITransactionScope, TransactionScope>();

            services.AddTransient<SqlSugarDBCom>();
            return services;
        }
    }
}
